package org.sgx.gwteditors.client.impl1.complex;

import java.util.LinkedList;
import java.util.List;

import org.sgx.gwteditors.client.editor.Editor;
import org.sgx.gwteditors.client.editor.error.EditorError;
import org.sgx.gwteditors.client.editor.error.EditorErrorManager;
import org.sgx.gwteditors.client.editor.event.EditorEventManager;
import org.sgx.gwteditors.client.editor.event.ValueChangeListener;
import org.sgx.gwteditors.client.impl1.EditorFramework1;
import org.sgx.gwteditors.client.impl1.EditorManager1;
import org.sgx.gwteditors.client.impl1.basetypes.SelectionList;
import org.sgx.gwteditors.client.util.Util;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class SelectionListSingleSelEditor<T> extends ListBox 
	implements Editor<SelectionList<T>>, ChangeHandler {

	private SelectionList<T> model;
	
	public SelectionListSingleSelEditor() {
		super();
	}
	@Override
	public void addValueChangeListener(ValueChangeListener<SelectionList<T>> l) {
		EditorEventManager.<SelectionList<T>>getInstance().addValueChangeListener(this, l);
	}

	@Override
	public void removeValueChangeListener(ValueChangeListener<SelectionList<T>> l) {
		EditorEventManager.<SelectionList<T>>getInstance().addValueChangeListener(this, l);
	}
	@Override
	public List<EditorError<SelectionList<T>>> getErrors() {
		return EditorErrorManager.<SelectionList<T>>getInstance().getErrors(this);
	}

	@Override
	public SelectionList<T> flush() {
		LinkedList<T> sel = new LinkedList<T>();
		T option = model.getItemNamed(getItemText(getSelectedIndex()));
		if(option!=null)
			sel.add(option);		
		model.setSelection(sel);
		return model;
	}

	@Override
	public void load(SelectionList<T> model) {
		if(model==null)
			return; 
		this.model=model;
		clear();
		int i = 0;
		for(T t : model.getOptions()) { 
			String s = t.toString();
			addItem(s);
			if(Util.contains(model.getSelection(), s)) {
				setItemSelected(i, true);
			}
			i++;
		}		
		addChangeHandler(this);
	}

	@Override
	public Widget getWidget() {
		return this;
	}

	@Override
	public boolean isSimple() {
		return true;
	}

	@Override
	public void onChange(ChangeEvent event) {
		EditorEventManager.<SelectionList<T>>getInstance().fireValueChangeEvent(this);
	}
	
	@Override
	public String getEditorId() {
		return EditorManager1.getInstance().getEditorName(this);		
	}

	@Override
	public String[] getEditorTypesSupported() {
		return new String[]{EditorFramework1.TYPE_LISTSINGLE}; 
		
	}
}
